import { hasComponent } from 'bitecs';
import { Collision, Impassable } from './components';
import { getPos2, move, onTile } from './pos2';
import { describe } from '$lib';
import { log } from './log';
import { Clock } from './clock';

export const MoveAction = (dx, dy, delay) => (world, e) => {
  return {
    error: false,
    action: () => {
      Clock.time[e] += delay;
      const { x, y } = getPos2(e);
      const x1 = x + dx;
      const y1 = y + dy;
      const col = onTile(world, x1, y1).filter(c =>
        hasComponent(world, Collision, c) || hasComponent(world, Impassable, c));
      if (col.length === 0) {
        move(world, e, x1, y1);
      } else {
        const tgt = col[0];
        log(`${describe(world, e)} bumps into ${describe(world, tgt)}`);
      }
    },
  };
};
